package com.podcstr.dao;

import com.podcstr.entity.Comment;
import org.apache.log4j.Logger;

import java.util.Date;
import java.util.List;

/**
 * @author azim
 * @since 5/16/13 
 */
public class CommentDaoImpl extends GenericDaoImpl<Comment, Long> implements CommentDao {

    private final Logger log = Logger.getLogger(CommentDaoImpl.class);

    @Override
    public List<Comment> findByPodcastId(long podcastId) {

        List<Comment> comments = getEntityManager().createQuery("SELECT c FROM Comment c WHERE c.podcast.id=:podcastId ORDER BY c.dateCreated desc")
                .setParameter("podcastId", podcastId).setMaxResults(10).getResultList();

        if (comments.size() != 0) {
            log.info(new Date() + " : Returning the list of comments with podcast id : " + podcastId);
        }

        return comments;
    }

    public long calculteRatingOfPodcast(long podcastId) {

        log.info(new Date() + " : Returning the average rating of the podcast with id : " + podcastId);

        Double ratingDouble = (Double) getEntityManager().createQuery("SELECT AVG(c.rating) FROM Comment c WHERE c.podcast.id=:podcastId")
                .setParameter("podcastId", podcastId).getSingleResult();
        if (ratingDouble == null) {
            return 0;
        }
        log.info(new Date() + " : The average rating is : " + Math.round(ratingDouble));
        return Math.round(ratingDouble);
    }
}
